package com.hw.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * servletUtil工具类
 * @author lipeng
 * @date 2022-09-09 11:21
 */
@Component
@Slf4j
public class ServletUtil {

    private static Environment environment;

    /**
     * 拿到request
     * @return
     */
    public static HttpServletRequest getRequest(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes.getRequest();
    }

    /**
     * 取当前服务器的ip
     * @return
     */
    public static String getHost(){
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            return localHost.getHostAddress();
        } catch (UnknownHostException e) {
            return "未取到host";
        }
    }

    /**
     * 拿到response
     * @return
     */
    public static HttpServletResponse getResponse(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes.getResponse();
    }


    /**
     * 是否移动端
     * @return
     */
    public static boolean isMobile(){
        HttpServletRequest request = ServletUtil.getRequest();
        String uaStr = request.getHeader("User-Agent").toLowerCase();
        UserAgent ua = UserAgentUtil.parse(uaStr);
        if (ua == null){
            return false;
        }
        return ua.isMobile();
    }

    /**
     * 获取客户端ip
     * @return
     */
    public static String clientIp(){
        HttpServletRequest request = ServletUtil.getRequest();
        // 优先取 X-Real-IP
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("x-forwarded-for");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("HTTP_X_WAF_REMOTE_ADDR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("HTTP_CUSREMOTEADDR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("X-Real-IP");
        }
        if (ip.contains(",")){
            ip = ip.split(",")[0];
        }
        return ip;
    }

    /**
     * 保存cookie
     * @param key
     * @param value
     * @param age
     */
    public static void setCookie(String key, String value, int age){
        HttpServletResponse response = ServletUtil.getResponse();
        key = ServletUtil.assembleCookieName(key);

        Cookie cookie = new Cookie(key, value);
        cookie.setDomain(ServletUtil.environment.resolvePlaceholders("${env.cookie-domain}"));
        cookie.setPath("/");
        cookie.setSecure(false);
        cookie.setMaxAge(age);
        response.addCookie(cookie);
    }

    /**
     * 取cookie
     * @param key
     * @return
     */
    public static String getCookie(String key){
        if (StrUtil.isBlank(key)){
            return null;
        }
        Cookie[] cookies = ServletUtil.getRequest().getCookies();
        if (cookies == null || cookies.length <= 0){
            return null;
        }
        key = ServletUtil.assembleCookieName(key);
        String value = null;
        for (Cookie cookie : cookies) {
            if (key.equals(cookie.getName())){
                value = cookie.getValue();
            }
        }
        return value;
    }

    /**
     * 拼接cookie的key
     * @param key
     * @return
     */
    public static String assembleCookieName(String key){
        return key;
    }

    /**
     * 取头信息中的某个字段
     * @param key
     * @return
     */
    public static String getHeader(String key){
        HttpServletRequest request = ServletUtil.getRequest();
        return request.getHeader(key);
    }
}
